<?php
defined('BASEPATH') OR exit('No direct script access allowed');
// +----------------------------------------------------------------------
// | 获取网站配置数据,钩子文件
// +----------------------------------------------------------------------
// | Copyright (c) 2015
// +----------------------------------------------------------------------
// | Author: baiping 125618036@qq.com http://www.webipcode.com
// +----------------------------------------------------------------------
// | 2015-7-10下午1:43:03
// +----------------------------------------------------------------------


/**
 * 钩子文件的作用：主要负责读取网站配置数据，前后台共用，在前后台的config/hooks.php中设置参数
 * 运行机制是先从缓存中获取网站配置数据，如果缓存中不存在，刚读取数据库，否则直接获取缓存数据
 *
 */
class Website {
	
	private  $CI;
	
	public function __construct(){
		$this->CI = &get_instance(); 
	}
	/**
	 * 获取网站配置数据
	 */
	public function getWebsite(){
		$this->CI->load->driver('cache',array('adapter' => 'apc', 'backup' => 'file'));//载入缓存,以文件形式存储
		$config_data = $this->CI->cache->get('config_data');//获取缓存,
		if ( !$config_data ){
			$this->CI->load->model('Config_model','conf');//加载config模型类
			$config_data = $this->CI->conf->getData(array('status' => 1), 'type,name,value');
			$config = array();
			if($config_data && is_array($config_data)){
				foreach ($config_data as $value) {
					$config[$value->name] = $this->parse($value->type, $value->value);
				}
			}
			//写入缓存
			$this->CI->cache->file->save('config_data', $config , 0);
		}else{
			$config = $this->CI->cache->get('config_data');
		}
	}
	
	/**
	 * 根据配置类型解析配置
	 * @param  integer $type  配置类型
	 * @param  string  $value 配置值
	 */
	private static function parse($type, $value){
		switch ($type) {
			case 3: //解析数组
				$array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
				if(strpos($value,':')){
					$value  = array();
					foreach ($array as $val) {
						list($k, $v) = explode(':', $val);
						$value[$k]   = $v;
					}
				}else{
					$value =    $array;
				}
				break;
		}
		return $value;
	}
	
}